﻿using System;
using System.Net.Mime;
using System.Text;
using System.Web;
using System.Web.Mvc;
using MiniWeb.Core.Dtos;
using MiniWeb.Core.Entities;
using MiniWeb.Core.Enums;
using MiniWeb.Task;
using System.Linq;
using MiniWeb.Web.Controllers.Code;
using MiniWeb.Web.Controllers.Web.web.ViewModels;
using WFramework;
using WFramework.Common;
using WFramework.Email;
using WFramework.MvcPager;
using WFramework.Utility;

namespace MiniWeb.Web.Controllers.Web.Home
{
    public class HomeController : BaseController
    {
        private readonly ProductsClassTask _productsClassTask = new ProductsClassTask();
        private readonly ProductsInfoTask _productsInfoTask = new ProductsInfoTask();
        private readonly NewsTask _newsTask = new NewsTask();
        private readonly AdConfigTask _adConfigTask = new AdConfigTask();
        private readonly WebLoginLogTask _webLoginLogTask = new WebLoginLogTask();
        private readonly AccountsInfoTask _accountsInfoTask = new AccountsInfoTask();

        public ActionResult Index()
        {
            //商品类目
           
            ViewData["typelist"] =_productsClassTask.GetClass();
            //广告轮播
            ViewData["AdList"] = _adConfigTask.GetAll(null, null);
            //公告
            ViewData["gonggaolist"] = _newsTask.GetPagedList(1, 1, null, null,1, 8);
            //橱窗位商品
            ViewData["chuchuanglist"] = _productsInfoTask.GetChuChuangList();

            //显示在首页的商品
            ViewData["ProductsForWebList"] = _productsInfoTask.GetWebList();

            return View();
        }


        public ActionResult login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(UserLogOnModel model, string returnUrl)
        {

            if (ModelState.IsValid)
            {
                //if (!_validateCodeService.CheckCode(model.ValidCode))
                //{
                //    _validateCodeService.ClearSession();
                //    return AlertMsg("验证码不正确", Request.UrlReferrer.ToString());

                //}

                var accountModel = _accountsInfoTask.GetByAccount(model.Account);
                if (accountModel == null)
                    return AlertMsg("账号不存在", Request.UrlReferrer.ToString());


                if (accountModel.Password != CryptTools.HashPassword(model.Pwd))
                    return AlertMsg("密码不正确", Request.UrlReferrer.ToString());

                accountModel.LastLoginIP = accountModel.ThisLoginIP;
                accountModel.LastLoginTime = accountModel.ThisLoginTime;

                accountModel.ThisLoginIP = DNTRequest.GetIP();
                accountModel.ThisLoginTime = DateTime.Now;
                _accountsInfoTask.Update(accountModel);

                // 添加登录日志
                _webLoginLogTask.CreateLog(model.Account, LoginTypeEnum.网站登录);
                WebFormsAuthService.SignIn(model.Account);
                return string.IsNullOrEmpty(returnUrl)
                         ? Redirect(Url.Action("Index", "Home"))
                         : Redirect(returnUrl);
            }

            return AlertMsg("缺少参数", Request.UrlReferrer.ToString());
        }


       
        public ActionResult Register()
        {
            return View();
        }

        public ActionResult ExitsName(string account)
        {
            var exitesaccount = _accountsInfoTask.ExistsAccount(account);
            return Json(!exitesaccount);
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model, string returnUrl)
        {
            
            if (string.IsNullOrEmpty(model.Account))
            {
               
                return Json(new { msg = -2, msgbox = "账号不能为空", url = "/home/index" });
            }
            if (model.Account.Length > 16)
            {
               
                return Json(new { msg = -2, msgbox = "账号过长", url = "/home/index" });
            }
            if (string.IsNullOrEmpty(model.Email))
            {
                return Json(new { msg = -2, msgbox = "邮箱不能为空", url = "/home/index" });
               

            }
            if (model.Pwd != model.CPwd)
            {
                return Json(new { msg = -2, msgbox = "密码不一致", url = "/home/index" });
                
            }
            if (ModelState.IsValid)
            {
                string msg = string.Empty;

                //if (!_validateCodeService.CheckCode(model.ValidCode))
                //    return AlertMsg("验证码不正确", Request.UrlReferrer.PathAndQuery);


                var accountmodel = new AccountsInfo
                {
                    Account = model.Account,
                    Password = CryptTools.HashPassword(model.Pwd),
                    HeadImg = "/img/defaultface.jpg",
                    RegIP = DNTRequest.GetIP(),
                    RegTime = DateTime.Now,
                    RegType = (int)RegTypeEnum.网站注册,
                    Phone = model.Phone,
                    Email = model.Email,
                };
                if (!_accountsInfoTask.Register(accountmodel, out msg))
                {
                  
                    return Json(new { msg = -2, msgbox = msg, url = "/home/index" });
                };

                // 添加登录日志
                _webLoginLogTask.CreateLog(model.Account, LoginTypeEnum.网站登录);

                WebFormsAuthService.SignIn(model.Account);
                return Json(new { msg = 1, url = "/home/index" });

            }
            return Json(new { msg = -2, msgbox = "参数出错", url = "/home/index" });
         

        }
        public ActionResult FindPwd()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SaveFindPwd(string account, string email)
        {
            if (string.IsNullOrEmpty(account) || string.IsNullOrEmpty(email))
            {
                return new EmptyResult();
            }
            var accountinfo = _accountsInfoTask.GetByAccount(account);
            if (accountinfo.Email != email)
            {
                return AlertMsg("账号和邮箱不对应", Request.UrlReferrer.ToString());
            }
            Random rnd = new Random();
            string rndpwd = rnd.Next(1000000, 99999999).ToString();
            MailInfo mailInfo = new MailInfo();

            mailInfo.ToEmailAddress.Add(accountinfo.Email);
            mailInfo.EmailSubject = "找回密码";
            mailInfo.EmailBody = @"&lt;p&gt;
	&lt;span&gt;&lt;span style=&quot;line-height:normal;&quot;&gt;&lt;br /&gt;
&lt;/span&gt;&lt;/span&gt; 
&lt;/p&gt;
&lt;p&gt;
	&lt;span&gt;&lt;span style=&quot;line-height:normal;&quot;&gt;&lt;br /&gt;
&lt;/span&gt;&lt;/span&gt; 
&lt;/p&gt;
&lt;p&gt;
	&lt;span&gt;&lt;span style=&quot;line-height:normal;&quot;&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;/span&gt; 
	&lt;table border=&quot;0&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; width=&quot;702&quot; class=&quot;responsive-table ke-zeroborder&quot; style=&quot;color:#000000;font-family:&#39;lucida Grande&#39;, Verdana, &#39;Microsoft YaHei&#39;;font-size:12px;border:1px solid #DEDEDE;margin:0px auto;background-color:#FFFFFF;&quot;&gt;
		&lt;tbody&gt;
			&lt;tr&gt;
				&lt;td bgcolor=&quot;#0373d6&quot; height=&quot;54&quot; align=&quot;center&quot; style=&quot;font-family:&#39;lucida Grande&#39;, Verdana, &#39;Microsoft YaHei&#39;;&quot;&gt;
					&lt;span style=&quot;font-size:32px;color:#FFFFFF;&quot;&gt;瓦西&lt;/span&gt; 
				&lt;/td&gt;
			&lt;/tr&gt;
			&lt;tr&gt;
				&lt;td bgcolor=&quot;#ffffff&quot; align=&quot;center&quot;&gt;
					&lt;p&gt;
						&lt;br /&gt;
					&lt;/p&gt;
					&lt;p&gt;
						&lt;span&gt;&lt;br /&gt;
&lt;/span&gt;
					&lt;/p&gt;
					&lt;table border=&quot;0&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; width=&quot;480&quot; class=&quot;responsive-table ke-zeroborder&quot; style=&quot;font-family:&#39;lucida Grande&#39;, Verdana, &#39;Microsoft YaHei&#39;;&quot;&gt;
						&lt;tbody&gt;
							&lt;tr&gt;
								&lt;td style=&quot;font-family:&#39;lucida Grande&#39;, Verdana, &#39;Microsoft YaHei&#39;;&quot;&gt;
									&lt;table width=&quot;100%&quot; border=&quot;0&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;ke-zeroborder&quot;&gt;
										&lt;tbody&gt;
											&lt;tr&gt;
												&lt;td style=&quot;font-family:&#39;lucida Grande&#39;, Verdana, &#39;Microsoft YaHei&#39;;&quot;&gt;
													&lt;table cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; border=&quot;0&quot; align=&quot;left&quot; class=&quot;responsive-table ke-zeroborder&quot;&gt;
														&lt;tbody&gt;
															&lt;tr&gt;
																&lt;td width=&quot;550&quot; align=&quot;left&quot; valign=&quot;top&quot; style=&quot;font-family:&#39;lucida Grande&#39;, Verdana, &#39;Microsoft YaHei&#39;;&quot;&gt;
																	&lt;table width=&quot;100%&quot; border=&quot;0&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;ke-zeroborder&quot;&gt;
																		&lt;tbody&gt;
																			&lt;tr&gt;
																				&lt;td bgcolor=&quot;#ffffff&quot; align=&quot;left&quot; style=&quot;font-family:&#39;lucida Grande&#39;, Verdana, &#39;Microsoft YaHei&#39;;font-size:17px;color:#7B7B7B;&quot;&gt;
																					&lt;b&gt;" + accountinfo.Account + @"，欢迎加入知乎!&lt;/b&gt; 
																				&lt;/td&gt;
																			&lt;/tr&gt;
																			&lt;tr&gt;
																				&lt;td align=&quot;left&quot; valign=&quot;top&quot; style=&quot;font-family:&#39;Hiragino Sans GB&#39;;font-size:14px;color:#7B7B7B;&quot;&gt;
																					欢迎使用瓦西网站，现密码更改为：
																				&lt;/td&gt;
																			&lt;/tr&gt;
																			&lt;tr&gt;
																				&lt;td align=&quot;center&quot; class=&quot;padding&quot; style=&quot;font-family:&#39;lucida Grande&#39;, Verdana, &#39;Microsoft YaHei&#39;;&quot;&gt;
																					" + rndpwd + @"
																				&lt;/td&gt;
																			&lt;/tr&gt;
																			&lt;tr&gt;
																				&lt;td align=&quot;left&quot; valign=&quot;top&quot; style=&quot;font-family:&#39;Hiragino Sans GB&#39;;font-size:14px;color:#7B7B7B;&quot;&gt;
																					请妥善保管您的账号信息,不要泄露给他人.：&lt;a href=&quot;www.wasy.com&quot; target=&quot;_blank&quot;&gt;www.wasy.com&lt;/a&gt; 
																				&lt;/td&gt;
																			&lt;/tr&gt;
																		&lt;/tbody&gt;
																	&lt;/table&gt;
																&lt;/td&gt;
															&lt;/tr&gt;
														&lt;/tbody&gt;
													&lt;/table&gt;
												&lt;/td&gt;
											&lt;/tr&gt;
										&lt;/tbody&gt;
									&lt;/table&gt;
								&lt;/td&gt;
							&lt;/tr&gt;
						&lt;/tbody&gt;
					&lt;/table&gt;
					&lt;p&gt;
						&lt;br /&gt;
					&lt;/p&gt;
				&lt;/td&gt;
			&lt;/tr&gt;
		&lt;/tbody&gt;
	&lt;/table&gt;
&lt;br /&gt;
&lt;/span&gt; 
&lt;/p&gt;
&lt;p&gt;
	&lt;span&gt;&lt;br /&gt;
&lt;/span&gt; 
&lt;/p&gt;
&lt;p&gt;
	&lt;span&gt;&lt;br /&gt;
&lt;/span&gt; 
&lt;/p&gt;
&lt;p&gt;
	&lt;span&gt;&lt;br /&gt;
&lt;/span&gt; 
&lt;/p&gt;
&lt;p&gt;
	&lt;span&gt;&lt;br /&gt;
&lt;/span&gt; 
&lt;/p&gt;
&lt;div style=&quot;font-family:&#39;lucida Grande&#39;, Verdana, &#39;Microsoft YaHei&#39;;font-size:14px;background-color:#FFFFFF;&quot;&gt;
	&lt;span&gt; &lt;/span&gt; 
&lt;/div&gt;
&lt;div style=&quot;font-family:&#39;lucida Grande&#39;, Verdana, &#39;Microsoft YaHei&#39;;font-size:14px;background-color:#FFFFFF;&quot;&gt;
	&lt;div&gt;
		&lt;span&gt;&lt;span&gt;&lt;strong&gt;&lt;/strong&gt;&lt;span style=&quot;font-size:9pt;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; 
	&lt;/div&gt;
	&lt;div&gt;
		&lt;span&gt;&lt;span&gt;&lt;strong&gt;&lt;/strong&gt;&lt;span style=&quot;font-size:9pt;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; 
	&lt;/div&gt;
&lt;/div&gt;";


            mailInfo.EmailPersonName = "姓名";
            mailInfo.IsBodyHtml = true;
            EmailUtility emailmanager = new EmailUtility();
            emailmanager.Send(mailInfo);
            accountinfo.Password = CryptTools.HashPassword(rndpwd);
            _accountsInfoTask.Update(accountinfo);

            return AlertMsg("新密码已发送到邮箱，请注意查收！", "/user/login");
        }


      

        public ActionResult LoginOut()
        {
            WebFormsAuthService.SignOut();
            return RedirectToAction("Index", "Home");
        }
        
    }
}
